<template>
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px">
  <el-form-item label="Show wait time" prop="enableWaitingTime">
    <el-switch v-model="ruleForm.enableWaitingTime"></el-switch>
  </el-form-item>

  <el-form-item label="Mins" prop="defaultWaitingTime">
    <TimeSelect v-model="ruleForm.defaultWaitingTime"></TimeSelect>
  </el-form-item>

  <el-card v-for="(waitTime, index) in ruleForm.peakWaitingTimes" :key="index">
    <el-form-item label="Mins" :prop="`peakWaitingTimes[${index}].waitingTime`" :rules="newRules.waitingTime">
      <TimeSelect v-model="waitTime.waitingTime"></TimeSelect>
    </el-form-item>
    <el-form-item label="开始时间" :prop="`peakWaitingTimes[${index}].fromTime`" :rules="newRules.fromTime">
      <el-time-select
        v-model="waitTime.fromTime"
        :picker-options="{
          start: '00:00',
          step: '00:05',
          end: '11:55'
        }"
        placeholder="选择开始时间"
      />
    </el-form-item>

    <el-form-item label="结束时间" :prop="`peakWaitingTimes[${index}].toTime`" :rules="newRules.toTime">
      <el-time-select
        v-model="waitTime.toTime"
        :picker-options="{
          start: '00:00',
          step: '00:05',
          end: '11:55',
        }"
        placeholder="选择结束时间"
      />
    </el-form-item>

    <el-form-item label="星期选择" :prop="`peakWaitingTimes[${index}].weeklySettings`" :rules="newRules.weeklySettings">
      <el-select v-model="waitTime.weeklySettings" multiple>
        <el-option
          v-for="item in weekOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
    </el-form-item>

    <el-button @click="delTime(index)">删除</el-button>
  </el-card>

  <el-button @click="addTime">增加</el-button>
  <el-button type="primary" @click="submit">提交表单</el-button>
</el-form>
</template>

<script>
import axios from 'axios'
import TimeSelect from 'components/TimeSelect'
import data from './data'

/**
 * 如果第二个时间大，返回 true
 */
function isTimeBefore(date, date1) {
  date = new Date('2020-11-11 ' + date)
  date1 = new Date('2020-11-11 ' + date1)
  return (date.getTime() - date1.getTime()) < 0
}

export default {
  name: 'Home',
  components: {
    TimeSelect,
  },
  data() {
    const validateToTime = (rule, value, callback) => {
      const index = Number(rule.field.replace(/[^0-9]/ig, ''))
      const fromTime = this.ruleForm.peakWaitingTimes[index].fromTime
      if (isTimeBefore(fromTime, value)) {
        callback()
      } else {
        callback(new Error('开始时间要小于结束时间'))
      }
    }

    const validateFromTime = (rule, value, callback) => {
      const index = Number(rule.field.replace(/[^0-9]/ig, ''))
      const toTime = this.ruleForm.peakWaitingTimes[index].toTime
      if (value && toTime) {
        this.$refs.ruleForm.validateField(`peakWaitingTimes[${index}].toTime`)
      }
      callback()
    }

    return {
      ruleForm: {
        enableWaitingTime: false,
        defaultWaitingTime: '',
        peakWaitingTimes: [],
      },
      rules: {
        defaultWaitingTime: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
      },
      newRules: {
        waitingTime: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
        fromTime: [
          { required: true, message: '请选择时间', trigger: 'blur' },
          { validator: validateFromTime, trigger: 'blur' }
        ],
        toTime: [
          { required: true, message: '请选择时间', trigger: 'blur' },
          { validator: validateToTime, trigger: 'blur' }
        ],
        weeklySettings: [
          { required: true, message: '请选择时间', trigger: 'change' },
        ],
      },
      weekOptions: [
        {
          label: 'Mon',
          value: 'monday',
        },
        {
          label: 'Tue',
          value: 'tuesday',
        },
        {
          label: 'Wed',
          value: 'wednesday',
        },
        {
          label: 'Thu',
          value: 'thursday',
        },
        {
          label: 'Fri',
          value: 'friday',
        },
        {
          label: 'Sat',
          value: 'saturday',
        },
        {
          label: 'Sun',
          value: 'sunday',
        },
      ],
    }
  },

  mounted() {
    this._setData()
  },

  methods: {
    _getAPi() {
      return localStorage.params ? JSON.parse(localStorage.params) : data
    },

    addTime() {
      this.ruleForm.peakWaitingTimes.push({
        waitingTime: '',
        fromTime: '',
        toTime: '',
        weeklySettings: [],
      })
    },

    delTime(index) {
      this.ruleForm.peakWaitingTimes.splice(index, 1)
    },

    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this._postFrom()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    _setData() {
      const res = this._getAPi()
      this.ruleForm = {
        enableWaitingTime: res.enableWaitingTime,
        defaultWaitingTime: res.defaultWaitingTime / 60,
        peakWaitingTimes: res.peakWaitingTimes.map(week => ({
          ...week,
          waitingTime: week.waitingTime / 60,
          weeklySettings: this._weekObjToArray(week.weeklySettings)
        })),
      }
    },

    _getData() {
      const {
        enableWaitingTime,
        defaultWaitingTime,
        peakWaitingTimes,
      } = this.ruleForm

      return {
        enableWaitingTime,
        defaultWaitingTime: defaultWaitingTime * 60,
        peakWaitingTimes: peakWaitingTimes.map(item => ({
          ...item,
          waitingTime: item.waitingTime * 60,
          weeklySettings: this._weekArrayToObj(item.weeklySettings)
        }))
      }
    },

    _postFrom() {
      const params = this._getData()
      localStorage.params = JSON.stringify(params)
    },

    /**
     * weekList，array: ['str1', 'str2']
     * return 对象（星期对象）
     */
    _weekArrayToObj(weekList) {
      const weeklyObj = {
        monday: false,
        tuesday: false,
        wednesday: false,
        thursday: false,
        friday: false,
        saturday: false,
        sunday: false,
      }
      weekList.forEach(key => {
        weeklyObj[key] = true
      })
      return weeklyObj
    },

    /**
     * weekObj: Object
     * return 星期数组
     */
    _weekObjToArray(weekObj) {
      return Object.keys(weekObj).filter(key => weekObj[key])
    },
  },
}
</script>
